﻿using B.S.NewMedical.Api.Write.Application.Command.Order.Consultation;
using B.S.NewMedical.Domain.Order;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.Order.Consultation
{
    /// <summary>
    /// 删除问诊记录处理器
    /// </summary>
    public class DeleteConsultationCommandHandle : IRequestHandler<DeleteConsultationCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ConsultationModel> _consultationRepository;
        private readonly ILogger<DeleteConsultationCommandHandle> _logger;

        public DeleteConsultationCommandHandle(
            IBaseRepository<ConsultationModel> consultationRepository,
            ILogger<DeleteConsultationCommandHandle> logger)
        {
            _consultationRepository = consultationRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(DeleteConsultationCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {


                // 1. 查找要删除的问诊记录
                var consultation = _consultationRepository.GetAll()
                    .FirstOrDefault(x => x.Id == request.Id && !x.IsDeleted);

                if (consultation == null)
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "未找到要删除的问诊记录";
                    _logger.LogWarning("未找到要删除的问诊记录，ID：{Id}", request.Id);
                    return result;
                }

                // 2. 检查问诊记录状态，防止删除已完成的问诊
                if (!string.IsNullOrEmpty(consultation.Orderstatus) &&
                    consultation.Orderstatus.Equals("已完成", StringComparison.OrdinalIgnoreCase))
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "已完成的问诊记录不能删除";
                    _logger.LogWarning("尝试删除已完成的问诊记录，ID：{Id}，状态：{Status}",
                        request.Id, consultation.Orderstatus);
                    return result;
                }

                // 3. 执行逻辑删除
                consultation.IsDeleted = true;
                consultation.UpdateTime = DateTime.Now;




                // 5. 更新数据库
                var updateResult = await _consultationRepository.UpdateAsync(consultation);

                if (updateResult > 0)
                {
                    result.Code = ApiEnum.Success;
                    result.Msg = "问诊记录删除成功";
                    result.Data = updateResult;


                }
                else
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "问诊记录删除失败";
                    result.Data = updateResult;


                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Error;
                result.Msg = $"删除问诊记录时发生异常：{ex.Message}";


            }

            return result;
        }
    }
}
